import {Token} from '../token';
import {Config} from 'config.js';

class Base{
	constructor()
	{
		this.baseRestUrl =Config.resUrl;
	}
	request(params,noRefetch,beforeHtml=='')
	{
		var that=this,
		    url=this.baseRestUrl+params.url;
		if(!params.type)
		{
			params.type='get';
		}    
		if(params.setUpUrl==false)
		{
			url=params.url;
		}
		$.ajax({  
		   url: url,  
		   data:params.data,
		   type: params.type,  
		   beforeSend: function (xhr) {  
			   xhr.setRequestHeader("token",localStorage.getItem("token")); 
			   beforeHtml;
		   },  
		   async: true,   
		   //contentType: 'application/x-www-form-urlencoded',  
		   success: function (res) {
				var code =res.statusCode.toString();
				var startChar = code.charAt(0);
				if(startChar == '2')
				{
					params.sCallback && params.sCallback(res.data);
				}else
				{
					if(code == '401')
					{
						if(!noRefetch)
						{
							that._refetch(params);
						}
					}
					that._processError(res);
					params.eCallback && params.eCallback(res.data);
				}
		   }
		   error:funciton(err)
		   {
			   that._processError(err);
		   }
				
		});  
	}
	_processError(err)
	{
		console.log(err);
	}
	_refetch(params)
	{
		var token = new Token();
		token.getTokenFromServer((token)=>{
			this.request(params,true);
		}); 
	}
	getDataSet(event,key)
	{
		return event.currentTarget.dataset[key];
	};
 

};

export {Base};
